package com.sphd.education.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.adapter.MyViewPagerAdapter;
import com.sphd.education.base.BaseFragment;
import com.sphd.education.info.DelInfo;
import com.sphd.education.info.MsgInfo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.interfaces.FragmentInterface;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 消息
 * Created by Administrator on 2015/10/12.
 */
public class MessageFragment extends BaseFragment implements ViewPager.OnPageChangeListener {
    @Bind(R.id.edit_msg)
    TextView editMsg;
    @Bind(R.id.tabs)
    TabLayout tabs;
    @Bind(R.id.vp_msg)
    ViewPager vpMsg;
    @Bind(R.id.del_layout)
    LinearLayout delLayout;
    @Bind(R.id.del_btn)
    Button delBtn;
    @Bind(R.id.cancel_btn)
    Button cancelBtn;
    private String Tag = "MessageFragment";
    private FragmentInterface fragmentInterface;
    private View rootView;
    private String titles[] = {"学校通知", "系统消息"};
    private MyViewPagerAdapter msgAdapter;
    private  Bundle bundle;
    private  List<Fragment> fragments;
    private  SchoolMsgsFragment schoolMsgsFragment;
    private  SystemMsgsFragment systemMsgsFragment;

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static MessageFragment newInstance(Bundle bundle) {
        MessageFragment fragment = new MessageFragment();
        fragment.setArguments(bundle);//传值判断是那个fragment
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(Tag, "onCreate");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_message_layout, container, false);
        Log.e(Tag, "onCreateView");
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }
    private void initView() {
        fragments = new ArrayList<>();
        bundle = new Bundle();
        schoolMsgsFragment=SchoolMsgsFragment.newInstance(bundle);
        systemMsgsFragment=SystemMsgsFragment.newInstance(bundle);
        fragments.add(schoolMsgsFragment);
        fragments.add(systemMsgsFragment);
        msgAdapter = new MyViewPagerAdapter(getChildFragmentManager(), titles, fragments);
        vpMsg.setAdapter(msgAdapter);
        // 设置ViewPager最大缓存的页面个数
//        idViewpager.setOffscreenPageLimit(7);
        // 给ViewPager添加页面动态监听器（为了让Toolbar中的Title可以变化相应的Tab的标题）
        tabs.setTabMode(TabLayout.MODE_FIXED);//MODE_FIXED按权重显示MODE_SCROLLABLE按具体大小显示
        // 将TabLayout和ViewPager进行关联，让两者联动起来
        tabs.setupWithViewPager(vpMsg);
        tabs.setTabTextColors(getResources().getColor(R.color.gray), getResources().getColor(R.color.white));
        // 设置Tablayout的Tab显示ViewPager的适配器中的getPageTitle函数获取到的标题
        tabs.setTabsFromPagerAdapter(msgAdapter);
        vpMsg.addOnPageChangeListener(this);
        vpMsg.setCurrentItem(0);
        editMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delLayout.setVisibility(View.VISIBLE);
                schoolMsgsFragment.ShowOrCloseCallback(true);
                systemMsgsFragment.ShowOrCloseCallback(true);
                DataSupport.deleteAll(DelInfo.class);
                systemMsgsFragment.setRefrshDate();
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delLayout.setVisibility(View.GONE);
                systemMsgsFragment.ShowOrCloseCallback(false);
                schoolMsgsFragment.ShowOrCloseCallback(false);
                DataSupport.deleteAll(DelInfo.class);
                systemMsgsFragment.setRefrshDate();
            }
        });
        delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<DelInfo> delInfos =DataSupport.findAll(DelInfo.class);
                if(delInfos.size()!=0){
                    for (int i=0;i<delInfos.size();i++){
                        if (delInfos.get(i).getDelId()!=0){
                            DataSupport.deleteAll(MsgInfo.class, "id=?", delInfos.get(i).getDelId()+"");
                        }
                    }
                    delLayout.setVisibility(View.GONE);
                    systemMsgsFragment.ShowOrCloseCallback(false);
                    DataSupport.deleteAll(DelInfo.class);
                    systemMsgsFragment.setRefrshDate();
                    StringBuffer stringBuffer =new StringBuffer();
                    List<String> list= schoolMsgsFragment.getDelList();
                    for (int i=0;i<list.size();i++){
                        stringBuffer.append(list.get(i));
                        Log.e("list====",list.get(i));
                    }
                    MyInfo myInfo =DataSupport.findLast(MyInfo.class);
                    String myUrl=EducationUrl.HttpTitle + EducationUrl.DELMSG +"memberId="+myInfo.getUserid()+stringBuffer.toString();
                    Log.e("myUrl=",myUrl);
                    StringRequest stringRequest =new StringRequest(Request.Method.POST,myUrl
                            , new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.e("response=",response);
                            schoolMsgsFragment.ShowOrCloseCallback(false);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                    EducationApplication.getRequestQueue().add(stringRequest);
                }else {
                    delLayout.setVisibility(View.GONE);
                    systemMsgsFragment.ShowOrCloseCallback(false);
                    schoolMsgsFragment.ShowOrCloseCallback(false);
                    DataSupport.deleteAll(DelInfo.class);
                    systemMsgsFragment.setRefrshDate();
                }

            }
        });
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.e(Tag, "onAttach");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e(Tag, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e(Tag, "onStop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(Tag, "onDestroy");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(Tag, "onDestroyView");
        ButterKnife.unbind(this);
    }

    // 接收activity传递过来的接口子类对象
    public void setCallBack(FragmentInterface fragmentInterface) {
        this.fragmentInterface = fragmentInterface;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void myNet() {

    }

    @Override
    public void getList(String string) {

    }

    @Override
    public void getList(JSONObject jsonObject) {

    }

    @Override
    public void getList(JSONArray jsonArray) {

    }
}
